﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Collections;

namespace EWDTAssignment
    {
    public partial class ShoppingCart : System.Web.UI.Page
        {

        decimal grandTotal = 0;
        protected void Page_Load(object sender, EventArgs e)
            {


            Session["accountID"] = "1";
            if (!IsPostBack)
                {
                if (Session["accountID"] != null)
                    {


                    gvShoppingCart.DataSourceID = "dsCartItem";
                    //Response.Redirect("ShoppingCart.aspx?");
                    //Display TempCart item
                    //Check if any item Add else Prompt Msg and redirect to home page
                    }
                else
                    {
                    DisplayAlert("Please Login First");
                    //   Response.Redirect("Home.aspx");
                    }
                }


            }



        protected void DisplayAlert(string message)
            {
            ClientScript.RegisterStartupScript(
        this.GetType(),
        Guid.NewGuid().ToString(),
        string.Format("alert('{0}')", message),
          true);

            }

        protected void DisplayAlertMsg(string message)
            {
            ClientScript.RegisterStartupScript(
        this.GetType(),
        Guid.NewGuid().ToString(),
        string.Format("alert('{0}');window.location.href = 'index.aspx'",
          message.Replace("'", @"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
          true);

            }


        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
            {

            }



        protected void btnDeleteItem_Click(object sender, EventArgs e)
            {
            if (!((CheckBox)gvShoppingCart.HeaderRow.FindControl("ckSelectAll")).Checked)
                {
                DisplayAlert("Please Select an item to Delete");

                }


            CheckBox ck;
            int numitem = 0;


            foreach (GridViewRow row in gvShoppingCart.Rows)
                {
                CheckBox chk;
                chk = (CheckBox)(row.Cells[0].FindControl("ck1"));


                ck = (CheckBox)row.FindControl("ck1");
                Label cartID = (Label)row.FindControl("lblCartID");

                if (ck.Checked)
                    {
                    string id = Session["accountID"].ToString();
                    numitem = App_Code.DBManager.DeleteCartItem(Convert.ToInt32(cartID.Text), Convert.ToInt32(id));

                    }
                }
            /*     if (numitem > 0)
                 {
                     string message = ("Item removed : " + numitem);
                     ClientScript.RegisterStartupScript(
     this.GetType(),
     Guid.NewGuid().ToString(),
     string.Format("alert('{0}')", message),
       true);}*/
            gvShoppingCart.DataSourceID = "dsCartItem";
            gvShoppingCart.DataBind();
            }


        protected void btnDeleteItem_Command(object sender, CommandEventArgs e)
            {


            }




       
        protected void LinkbtnEditCart_Click(object sender, EventArgs e)
            {



            }

        protected void gvShoppingCart_RowCreated(object sender, GridViewRowEventArgs e)
            {


            }




        protected void gvShoppingCart_RowCommand(object sender, GridViewCommandEventArgs e)
            {

            }

        protected void lkbtnPName_Click(object sender, EventArgs e)
            {


            }

        protected void ckSelectAll_CheckedChanged(object sender, EventArgs e)
            {
            CheckBox chk;

            //if (IsPostBack)
            //  {
            //Make all ChebkBox checked
            if (Session["checked"] == null || Session["checked"].ToString() == "0")
                {

                foreach (GridViewRow rowItem in gvShoppingCart.Rows)
                    {
                    chk = (CheckBox)(rowItem.Cells[0].FindControl("ck1"));
                    chk.Checked = false;

                    }
                chk = (CheckBox)gvShoppingCart.HeaderRow.FindControl("ckSelectAll");
                CheckBox ftchkbx = (CheckBox)gvShoppingCart.FooterRow.FindControl("ckSelectAll");
                ftchkbx.Checked = false;
                chk.Checked = false;
                Session["checked"] = "1";

                }
            else if (Session["checked"].ToString() == "1")
                {
                foreach (GridViewRow rowItem in gvShoppingCart.Rows)
                    {
                    chk = (CheckBox)(rowItem.Cells[0].FindControl("ck1"));
                    chk.Checked = ((CheckBox)sender).Checked;
                    }
                Session["checked"] = "0";

                chk = (CheckBox)gvShoppingCart.HeaderRow.FindControl("ckSelectAll");
                CheckBox ftchkbx = (CheckBox)gvShoppingCart.FooterRow.FindControl("ckSelectAll");
                ftchkbx.Checked = ((CheckBox)sender).Checked;
                chk.Checked = ((CheckBox)sender).Checked;


                }
            UpdateSelectedToGrandTotal();
            }

        protected void gvShoppingCart_RowEditing(object sender, GridViewEditEventArgs e)
            {
            //get current cartID in Edit row
            Label cartProductID = (Label)gvShoppingCart.Rows[e.NewEditIndex].FindControl("lblProductID");
            Session["cartProductID"] = cartProductID.Text;
            //get selected value in ddlQty


            }

        protected void LinkbtnCancelCart_Click(object sender, EventArgs e)
            {



            }

        //Update QTY on Shopping Cart 
        protected void gvShoppingCart_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
            TextBox txtbxQty = (TextBox)gvShoppingCart.Rows[e.RowIndex].FindControl("txtboxQty");
            Session["cartQty"] = txtbxQty.Text;
            Label lblcartProductID = (Label)gvShoppingCart.Rows[e.RowIndex].FindControl("lblProductID");
            int accID = Convert.ToInt32(Session["accountID"].ToString());
            int cartProductID = Convert.ToInt32(lblcartProductID.Text);

            int newQTy = Convert.ToInt32(Session["cartQty"].ToString());
            App_Code.DBManager.EditQtyInCartItem(accID, cartProductID, "", 0, newQTy, 0);

            }

        protected void gvShoppingCart_RowUpdated(object sender, GridViewUpdatedEventArgs e)
            {



            }

     


        protected void gvShoppingCart_RowDataBound(object sender, GridViewRowEventArgs e)
            {
       
            int qq = gvShoppingCart.PageCount; //get total page number and calc the price


            if (e.Row.RowType == DataControlRowType.DataRow)
                { // Label qty = (Label)e.Row.FindControl("lblQty");
                //  Label price = (Label)e.Row.FindControl("lblPrice");
              
                decimal price = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Price"));
                decimal qty = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "CartQty"));
                decimal perItemTotal = price * qty;
                Label stotal = (Label)e.Row.FindControl("lblTotalItemPrice");
                stotal.Text = perItemTotal.ToString();
                grandTotal = grandTotal + perItemTotal;

                }
            if (e.Row.RowType == DataControlRowType.Footer)
                {
                Label grdtotal = (Label)e.Row.FindControl("lblgrdtotal");
                grdtotal.Text = grandTotal.ToString("c");

                }
            }

        protected void ck1_CheckedChanged(object sender, EventArgs e)
            {

            UpdateSelectedToGrandTotal();

            }

        protected void UpdateSelectedToGrandTotal()
            {
            decimal grandTotal2 = 0;
       
            foreach (GridViewRow row in gvShoppingCart.Rows)
                {
                if (((CheckBox)row.FindControl("ck1")).Checked == true)
                    {
                    Label lblsubtotal = (Label)row.FindControl("lbltotalitemPrice");
                    decimal subtotal = Convert.ToDecimal(lblsubtotal.Text);
                    grandTotal2 += subtotal;
                    }
                }

            Label lblGrandTotal = (Label)gvShoppingCart.FooterRow.FindControl("lblGrdTotal");
            lblGrandTotal.Text = string.Format("{0:C}", grandTotal2);
            }

        protected void imgBtnDelete_Click(object sender, ImageClickEventArgs e)
            {
            if (!((CheckBox)gvShoppingCart.HeaderRow.FindControl("ckSelectAll")).Checked)
                {
                DisplayAlert("Please Select an item to Delete");

                }


            CheckBox ck;
            int numitem = 0;


            foreach (GridViewRow row in gvShoppingCart.Rows)
                {
                CheckBox chk;
                chk = (CheckBox)(row.Cells[0].FindControl("ck1"));


                ck = (CheckBox)row.FindControl("ck1");
                Label pID = (Label)row.FindControl("lblProductID");

                if (ck.Checked)
                    {
                    string id = Session["accountID"].ToString();
                    numitem = App_Code.DBManager.DeleteCartItem(Convert.ToInt32(pID.Text), Convert.ToInt32(id));//test

                    }
                }
          
            gvShoppingCart.DataSourceID = "dsCartItem";
            gvShoppingCart.DataBind();

        
            }

        protected void gvShoppingCart_SelectedIndexChanged(object sender, EventArgs e)
            {
                
            }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
            {
            CheckBox ck;
            Dictionary<int, int> checkoutItem = new Dictionary<int, int>();
            foreach (GridViewRow row in gvShoppingCart.Rows)
                {
               


                ck = (CheckBox)row.FindControl("ck1");
              

                if (ck.Checked)
                    {
                    Label lblpID = (Label)row.FindControl("lblproductID");
                    Label lblpQty = (Label)row.FindControl("lblcartQty");
                    checkoutItem.Add(int.Parse(lblpID.Text), int.Parse(lblpQty.Text));
                    }

                }

            Session["checkoutList"] = checkoutItem;
        Label gtotal = (Label)    gvShoppingCart.FooterRow.FindControl("lblGrdtotal");
        Session["checkoutGtotal"] = double.Parse(gtotal.Text);
        Response.Redirect("confirmation1.aspx");

            }

  
       


        }
    }